/**
 * 支付产品公用js
 * @author  xn pay
 * @date 090724
 */
/**
 * 兼容早期版本 不能去掉
 * @param {Object} id
 */
function $(id){
    if (document.id) {
        return document.id;
    } else {
        return document.getElementById(id);
    }
}

//去除左右空格和0
String.prototype.trim = function(){
    return this.replace(/(^\s+)|(\s+$)/g, "");
}
String.prototype.trimZero = function(){
    return this.replace(/\b(0+)/gi, "")
};

/**
 * 检查是不是手机号码
 * @param {String} number
 * ＠return true或者false
 */
function isPhone(number){
    var reg = /^1[358]\d{9}$/;
    return reg.test(number);
}

/**
 * 检查是不是中国移动号码
 * @param {String} number
 * @return  true 或者false
 */
function checkCMCC(number){
    var reg = /^1(3[4-9]\d{8}|5[021789]\d{8}|8[78]\d{8})$/;
    return reg.test(number);
}

/**
 * 检查是否是联通手机
 * @param {String} number
 * ＠return true或者false
 */
function checkUnicom(number){
    var reg = /^1(3[0-3]\d{8}|5[36]\d{8}|8[56]\d{8})$/;
    return reg.test(number);
}


/**
 * 检测移动手机
 * @param {String} number
 * @return 
 */
function  checkFormNumber(number){
	this.lang = {
			INCORRCT:"致命错误",
			NOTNUMBER : "这不是手机号码,请输入手机号码",
			EMPTY : "手机号码不能为空，请输入手机号码",
			WRONGLENGTH:'手机号码位数不正确',
			INCAPABLE:'无法识别的手机号码',
			NOMOBILE:'不是移动手机号码',
			ISRIGHT:'输入正确'
	};
	var o =number;
	o = o.trim();
	if(o.length == 0) {
		return this.lang.EMPTY;
	}
	if(!isPhone(o)){
		return this.lang.NOTNUMBER;
	}
	if (!checkCMCC(o)) {
		return this.lang.NOMOBILE;
	}
	return "";
}
/**
 * 创建PAY对象
 */
if (typeof(PAY) == 'undefined') {
    var PAY = {};
}
PAY.Event = {
    addEvent: function(obj, type, func){
        if (obj.addEventListener) {
            obj.addEventListener(type, func, false);
        } else if (obj.attachEvent) {
            obj.attachEvent("on" + type, func);
        }
    },
    delEvent: function(obj, type, func){
        if (obj.removeEventListener) {
            obj.removeEventListener(type, func, false);
        } else if (obj.dettachEvent) {
            obj.dettachEvent("on" + type, func);
        }
    },
    pointerX: function(){
    
    }
}
PAY.Do = {
    alert: function(title, message, y, n, closewin, hidebutton){
        var y = y || "确定";
        var dialog;
        if ($("pay_dialog")) {
            dialog = $("pay_dialog");
            if (dialog.style.display == "none") 
                dialog.style.display = "block";
        } else {
            dialog = document.createElement("div");
            dialog.id = "pay_dialog";
            dialog.style.position = "absolute";
            dialog.style.zIndex = 10000;
            dialog.style.width = "400px";
            document.body.appendChild(dialog);
        }
        dialog.innerHTML = '<table style="width: 100%; height: 100%;" class="pop_dialog_table">' +
        '<tr><td class="pop_topleft"></td><td class="pop_border"></td><td class="pop_topright"></td></tr>' +
        '<tr><td class="pop_border"></td><td class="pop_content"><h2><a href="javascript:void 0" class="p_close_link" id="p_close_link">关闭</a><span>' +
        title +
        '</span></h2>' +
        '<div class="dialog_content"><div class="dialog_body">' +
        message +
        '</div>' +
        '<div class="dialog_buttons" id="dialog_buttons"><input type="button" id="close_btn" class="input-submit" value=' +
        y +
        ' />' +
        (n == null ? '' : ' <input type="button" id="pay_n_btn" class="input-submit gray" value=' + n + ' />') +
        '</div></div></td><td class="pop_border"></td></tr>' +
        '<tr><td class="pop_bottomleft"></td><td class="pop_border"></td><td class="pop_bottomright"></td></tr>' +
        '</table>';
        setTimeout(function(){
            $("close_btn").onclick = $("p_close_link").onclick = function(){
                if (PAY.Dom.disabled) {
                    PAY.Dom.enable();
                }
                dialog.style.display = "none";
            }
        }, 10);
        if (hidebutton) {
            $("dialog_buttons").style.display = "none";
        }
        if (!closewin) {
            $("p_close_link").style.display = "none";
        }
        var doc = document.documentElement || document.body;
        var _w = doc.clientWidth;
        var _h = doc.clientHeight;
        var x = Math.floor((_w - 400) / 2) + doc.scrollLeft;
        var y = Math.floor((_h - dialog.offsetHeight) / 2) + doc.scrollTop;
        dialog.style.left = x + "px";
        dialog.style.top = y + "px";
    },
    close: function(){
        if ($("pay_dialog")) {
            dialog = $("pay_dialog");
            dialog.style.display = "none";
            return;
        }
    },
    html: function(val){
        if ($("pay_dialog")) {
            JQ('.dialog_body').html(val);
        }
    }
}
PAY.Dom = {
    realLeft: function(element, parent){
        var parent = parent || document.body;
        if (!element.offsetParent || element.offsetParent == parent) 
            return element.offsetLeft;
        else {
            var rl = 0;
            var p = element;
            while (p != null && p != parent) {
                rl += p.offsetLeft;
                p = p.offsetParent;
            }
            return rl;
        }
    },
    realTop: function(element, parent){
        var parent = parent || document.body;
        if (!element.offsetParent || element.offsetParent == parent) {
            return element.offsetTop;
        } else {
            var rt = 0;
            var p = element;
            while (p != null && p != parent) {
                rt += p.offsetTop;
                p = p.offsetParent;
            }
        }
        return rt;
    },
    disable: function(){
        if (!$("pay_overlay")) {
            var overlay = document.createElement("div");
            overlay.className = overlay.id = "pay_overlay";
            overlay.style.height = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) + 200 + "px";
            document.body.appendChild(overlay);
        } else {
            $("pay_overlay").style.display = "";
        }
        this.disabled = true;
    },
    enable: function(){
        if (this.disabled) {
            $("pay_overlay").style.display = "none";
        }
        this.disabled = false;
    }
}
PAY.Ajax = function(){
    this.req = {};
}
PAY.Ajax.prototype.request = function(url, param, method, onSucc, onFail){
    this.onSucc = onSucc;
    this.onFail = onFail;
    if (window.XMLHttpRequest) {
        this.req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            this.req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            this.req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!this.req) 
        return false;
    if (method == "get") {
        url += (/\?/.test(url)) ? ("&") : ("?" + param);
    }
    var s = this;
    this.req.open(method, url, true);
    this.req.onreadystatechange = function(){
        s.processChange();
    }
    this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    this.req.send(method == "get" ? null : param);
};
PAY.Ajax.prototype.processChange = function(){
    if (this.req.readyState == 4) {
        if (this.req.status == 200) {
            this.onSucc(this.req);
        } else {
            this.onFail(this.req.status);
        }
    }
};
if (typeof(autoSuggest) == 'undefined') {
    var autoSuggest = {};
}
autoSuggest = function(input, opts){
    if (!document.getElementById || !$(input)) 
        return;
    this.input = $(input);
    for (var p in opts) {
        this[p] = opts[p];
    }
    this.init();
}
autoSuggest.prototype = {
    searchDelay: 0.5,
    _inputTimer: null,
    friendsMatch: [],
    _ul: null,
    li_null: null,
    aslihoverClass: 'as_highlight',
    defaultPhoto: 'http://xnimg.cn/xnapp/pay/img/photo_default.jpg',
    lastInput: '',
    returned: false,
    inputTip: "请输入好友姓名",
    _liHasHighlight: null,
    returnedLi: null,
    _checkInput: function(){
        var cv = this.input.value;
        if (cv == '' || cv == this.inputTip) {
            this.hideMenu();
            return;
        }
        if (cv == this.lastInput) 
            return;
        this.lastInput = cv;
        this.buildMenu(cv);
    },
    setInputTip: function(){
        if (this.input.value == '') {
            this.input.value = this.inputTip;
        }
    },
    _inputOnKeyDown: function(e){
        var e = e || window.event;
        var li;
        switch (e.keyCode) {
            case 38://向上高亮
                if (this._liHasHighlight && this._liHasHighlight.previousSibling) {
                    li = this._liHasHighlight.previousSibling;
                } else {
                    li = this._ul.lastChild;
                }
                this._highLightMenu(li);
                return false;
                break;
            case 40://向下高亮
                if (this._liHasHighlight && this._liHasHighlight.nextSibling) {
                    li = this._liHasHighlight.nextSibling;
                } else {
                    li = this._ul.firstChild;
                }
                this._highLightMenu(li);
                return false;
                break;
            case 13://按回车键
                if (this._liHasHighlight) {
                    this._selectMenu(this._liHasHighlight);
                    this.input.blur();
                }
                return false;
                break;
            case 27://按ESC取消
                this.input.blur();
        }
    },
    _highLightMenu: function(li){
        if (this._liHasHighlight == li || !li) 
            return;
        if (this._liHasHighlight != null) {
            this._liHasHighlight.className = '';
        }
        li.className = this.aslihoverClass;
        this._liHasHighlight = li;
        if (li.bgphoto) {
            $("friend_photo").style.backgroundImage = "url(" + li.bgphoto + ")";
        } else {
            $("friend_photo").style.backgroundImage = "url(" + this.defaultPhoto + ")";
        }
    },
    _selectMenu: function(li){
        this.returned = true;
        this.returnedLi = li;
        this.lastInput = this.input.value = li.asname;
        $("friend_id").value = li.friendid;
        $("friend_photo").style.backgroundImage = "url(" + li.bgphoto + ")";
        if (li == this.li_null) {
            this.returned = false;
            this.returnedLi = this.li_null;
        }
    },
    hideMenu: function(){
        this._ul.style.display = "none";
        this._ul.innerHTML = "";
    },
    showMenu: function(){
        this._ul.style.display = '';
    },
    buildMenu: function(cv){
        var s = this;
        var myAjax = new PAY.Ajax();
        var p = '{"init":false,"qkey":"friend","uid":true,"uname":true,"uhead":true,"limit":24,"param":{},"query":"' + cv + '","group":"","net":""}';
        myAjax.request("/friendsSelector.do", "p=" + encodeURIComponent(p), "post", function(o){
            s._buildMenu.call(s, o);
        }, function(){
            PAY.Do.alert('提示', '加载好友失败，请稍候再试...');
        });
    },
    _buildMenu: function(list){
        var friendlist = eval("(" + list.responseText + ")").candidate;
        this.friendsMatch = friendlist;
        if (friendlist.length > 0) 
            this.createList(friendlist);
        this._highLightMenu(this._ul.firstChild);
    },
    createList: function(friendsMatch){
        var lis = [];
        var lis_frg = document.createDocumentFragment();
        for (var i = 0; i < friendsMatch.length; i++) {
            var li = document.createElement("li");
            li.asid = i;
            li.friendid = friendsMatch[i].id;
            li.bgphoto = friendsMatch[i].head;
            li.asname = friendsMatch[i].name;
            li.appendChild(document.createTextNode(friendsMatch[i].name));
            lis_frg.appendChild(li);
        }
        this._ul.innerHTML = '';
        this._ul.appendChild(lis_frg);
        this.showMenu();
    },
    clearInterval: function(){
        if (this._inputTimer) {
            clearInterval(this._inputTimer);
            this._inputTimer = null;
        }
    },
    setInterval: function(){
        var s = this;
        this._inputTimer = setInterval(function(){
            s._checkInput();
        }, s.searchDelay * 1000);
    },
    _menuOnclick: function(e){
        this.returnedLi = this._liHasHighlight;
        this._selectMenu(this._liHasHighlight);
    },
    _menuOnmouseover: function(e){
        var et = e.target || e.srcElement;
        var li;
        if (et.tagName.toLowerCase() == "li") {
            li = et;
        } else if (et.parentNode.tagName.toLowerCase() == "li") {
            li = et.parentNode;
        }
        if (li) 
            this._highLightMenu(li);
        return false;
    },
    initMenu: function(){
        var ul = document.createElement("ul");
        ul.id = "as_ul";
        ul.className = "as_ul";
        var x = PAY.Dom.realLeft(this.input);
        var y = PAY.Dom.realTop(this.input);
        ul.style.left = x + "px";
        ul.style.top = y + this.input.offsetHeight - 1 + "px";
        document.body.appendChild(ul);
        this._ul = ul;
        var s = this;
        this._ul.onclick = function(e){
            var e = e || window.event;
            s._menuOnclick(e);
        }
        this._ul.onmousemove = function(e){
            var e = e || window.event;
            s._menuOnmouseover(e);
        }
        var li_null = document.createElement("li");
        li_null.asid = li_null.friendid = li_null.asname = '';
        li_null.bgphoto = this.defaultPhoto;
        this.li_null = li_null;
        this.hideMenu();
    },
    checkReturn: function(){
        var s = this;
        window.setTimeout(function(){
            if (!s.returned) {
                s.input.value = '';
                s.setInputTip();
                $("friend_photo").style.backgroundImage = "url(" + s.defaultPhoto + ")";
            } else {
                s._selectMenu(s.returnedLi);
            }
            s.hideMenu();
        }, 200);
        if (this.input.value == "") {
            this._selectMenu(this.li_null);
        }
    },
    init: function(){
        var input = this.input;
        this.input.value = this.inputTip;
        var s = this;
        this.initMenu();
        this._checkInput();
        input.setAttribute("autocomplete", "off");
        //PAY.Event.addEvent(input, "focus", function(){s._inputTimer = setInterval(function(){s._checkInput.call(s);}, s.searchDelay*1000);});
        input.onfocus = function(){
            s.setInterval();
            if (s.inputTip == this.value) {
                this.value = '';
            }
        }
        input.onblur = function(){
            s.clearInterval();
            s.checkReturn();
            s.setInputTip();
        }
        input.onkeydown = function(e){
            return s._inputOnKeyDown(e);
        }
    }
};

/*
 * 帮助页面使用
*   update:支持新的tab标签显示 
 */
function tabView(){
    var lis = $("tabs").getElementsByTagName("li");
    var link = $("tabs").getElementsByTagName("a");
    var h3 = $("titles").getElementsByTagName("h3");
    var imgs = $("pics").getElementsByTagName("img");
    var n = lis.length;
    var cur = 0;
    imgs[cur].style.display = "block";
    imgs[n - 1].style.cursor = "default";
    h3[cur].style.display = "block";
    for (i = 0; i < imgs.length; i++) {
        (function(){
            imgs[i].id = "img_li_" + i; //为里面的图片增加ID
            imgs[i].key = i;
        })();
    }
    for (i = 0; i < imgs.length; i++) {
        (function(){
            lis[i].id = "li_" + i; //为li增加ID
            lis[i].key = i;
        })();
    }
    for (i = 0; i < imgs.length; i++) {
        (function(){
            h3[i].id = "h3_li_" + i; //为li增加ID
            h3[i].key = i;
        })();
    }
    //让链接失去焦点
    for (var key in link) {
        link[key].onclick = function(){
            this.blur();
        }
    }
    
    for (var key in lis) {
        lis[key].onclick = function(){
            for (k = 0; k < n; k++) {
                lis[k].className = "";
                var obj = imgs[k];
                obj.style.display = "none";
                var h = h3[k];
                h.style.display = "none";
            }
            //如果存在下一个标签卡，改变下一个标签卡
            if ($("li_" + (this.key + 1))) {
                this.className = "current";
                $("img_" + this.id).style.display = "block";
                $("img_" + this.id).src = $("img_" + this.id).src;
                $("h3_" + this.id).style.display = "block";
                $("li_" + (this.key + 1)).style.marginLeft = "-1px";
                $("li_" + (this.key + 1)).className = "following";
            } else {
                this.className = "last";
                $("img_" + this.id).style.display = "block";
                $("img_" + this.id).src = $("img_" + this.id).src;
                $("h3_" + this.id).style.display = "block";
            }
        }
    }
    for (i = 0; i < n - 1; i++) {
        (function(){
            imgs[i].onclick = function(){
                this.style.display = "none";
                var next = "img_li_" + (this.key + 1);
                $("li_" + this.key).className = "";
                //如果存在下一个标签卡，改变下一个标签卡
                if ($("li_" + (this.key + 2))) {
                    $("li_" + (this.key + 1)).className = "current";
                    $("h3_li_" + this.key).style.display = "none";
                    $("h3_li_" + (this.key + 1)).style.display = "block";
                    $("li_" + (this.key + 2)).style.marginLeft = "-1px";
                    $("li_" + (this.key + 2)).className = "following";
                } else {
                    $("li_" + (this.key + 1)).className = "last";
                    $("h3_li_" + this.key).style.display = "none";
                    $("h3_li_" + (this.key + 1)).style.display = "block";
                }
                if ($(next)) {
                    $(next).style.display = "block";
                    $(next).src = $(next).src;
                }
            }
        })();
    }
}

function initMenu(){
    if (document.all) {
        var page = window.location.href.replace("#", "");
    } else {
        var s = window.location.href.split("/");
        var page = s[s.length - 1].replace("#", "");
    }
    var lis = $("pay_tab").getElementsByTagName("li");
    var n = lis.length;
    (function(){
        for (i = 0; i < n; i++) {
            lis[i].className = "";
            var s = lis[i].getElementsByTagName("a");
            var l = s[0].attributes['href'].value;
            
            if (page == l) {
                lis[i].className = "selected";
            }
        }
    })();
}

/*创建一个客服的iframe*/
function triggerIframe(){
    var iframe = '<iframe id="customService" marginwidth="0" marginheight="0" scrolling="no" framespacing="0" vspace="0" hspace="0" frameborder="0" width="100" height="24" src="http://game.renren.com/online.html?v=1"></iframe>';
    JQ("#service").after(iframe);
}

/**
 * 关闭当前弹窗
 * @param {Object} time
 */
var intval;
function close_win(time){
	var t = time || 5000;
	intval = setTimeout(function(){opener=null;self.close();},t);
}

/*进度条提示*/
var intval = null;
var w = 0;
var retryTimes = 0;
var runLength = 1;
function runProgress(time){
    clearInterval(intval);
    runLength = 1;
    w = 0;
    JQ("#progressBar").show();
    JQ("#loadingTip").show();
    JQ("#warning-msg").show();
    JQ("#retry").hide();
    JQ("#progress").width(runLength);
    runLength = parseInt(274 / (time * 2));
    intval = setInterval(go, 500);
}


var go = function(){
    w += runLength;
    if (w <= 274) {
        JQ("#progress").width(w);
    } else {
        clearInterval(intval);
        showMobileRetry();
    }
}

